document.addEventListener('DOMContentLoaded', function() {
    const searchForm = document.getElementById('searchForm');
    const resetBtn = document.getElementById('resetBtn');
    const downloadBtn = document.getElementById('downloadBtn');
    const searchResults = document.getElementById('searchResults');
    const resultsContainer = document.getElementById('resultsContainer');
    const searchType = document.getElementById('searchType');
    const categoryGroup = document.getElementById('categoryGroup');
    
    let currentResults = [];
    
    // 搜索表单提交
    searchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        performSearch();
    });
    
    // 重置按钮
    resetBtn.addEventListener('click', function() {
        searchForm.reset();
        searchResults.style.display = 'none';
        downloadBtn.style.display = 'none';
    });
    
    // 下载按钮
    downloadBtn.addEventListener('click', function() {
        downloadResults();
    });

    function updateCategoryVisibility() {
        if (searchType.value === 'ingredient') {
            categoryGroup.style.display = '';
        } else {
            categoryGroup.style.display = 'none';
        }
    }
    updateCategoryVisibility();
    searchType.addEventListener('change', updateCategoryVisibility);
    
    async function performSearch() {
        const formData = new FormData(searchForm);
        const searchParams = Object.fromEntries(formData);
        
        try {
            // 调用后端API获取数据
            const allData = await fetchAllData();
            const filteredData = filterData(allData, searchParams);
            
            displayResults(filteredData);
            currentResults = filteredData;
            
            if (filteredData.length > 0) {
                downloadBtn.style.display = 'inline-block';
            } else {
                downloadBtn.style.display = 'none';
            }
        } catch (error) {
            console.error('搜索失败:', error);
            alert('搜索失败，请稍后重试');
        }
    }
    
    async function fetchAllData() {
        const allData = [];
        const formData = new FormData(searchForm);
        const searchParams = Object.fromEntries(formData);
        
        try {
            // 构建查询参数
            const queryParams = new URLSearchParams();
            if (searchParams.searchName) queryParams.append('searchName', searchParams.searchName);
            if (searchParams.startDate) queryParams.append('startDate', searchParams.startDate);
            if (searchParams.endDate) queryParams.append('endDate', searchParams.endDate);
            
            // 获取食物数据
            const foodsUrl = searchParams.searchType === 'all' || searchParams.searchType === 'food' || !searchParams.searchType 
                ? `http://localhost:3000/api/foods?${queryParams.toString()}`
                : null;
            
            if (foodsUrl) {
                const foodsResponse = await fetch(foodsUrl);
                if (foodsResponse.ok) {
                    const foods = await foodsResponse.json();
                    foods.forEach(food => {
                        allData.push({
                            type: 'food',
                            id: food.id,
                            name: food.name,
                            description: food.description,
                            created_at: food.created_at,
                            photo: food.photo,
                            origin: food.origin || '未知',
                            productionDate: food.production_date || (food.created_at ? food.created_at.split('T')[0] : ''),
                            producer: food.producer || '未知',
                            season: food.season || '未知'
                        });
                    });
                }
            }
            
            // 获取食材数据
            const ingredientsUrl = searchParams.searchType === 'all' || searchParams.searchType === 'ingredient' || !searchParams.searchType 
                ? `http://localhost:3000/api/ingredients?${queryParams.toString()}`
                : null;
            
            if (ingredientsUrl) {
                const ingredientsResponse = await fetch(ingredientsUrl);
                if (ingredientsResponse.ok) {
                    const ingredients = await ingredientsResponse.json();
                    ingredients.forEach(ingredient => {
                        allData.push({
                            type: 'ingredient',
                            id: ingredient.id,
                            name: ingredient.name,
                            description: ingredient.description,
                            created_at: ingredient.created_at,
                            photo: ingredient.photo,
                            origin: ingredient.origin || '未知',
                            productionDate: ingredient.production_date || (ingredient.created_at ? ingredient.created_at.split('T')[0] : ''),
                            producer: ingredient.producer || '未知',
                            category: ingredient.category || '未分类',
                            price: ingredient.price || '',
                            supplier: ingredient.supplier || '',
                        });
                    });
                }
            }
            
            // 获取食品数据
            const productsUrl = searchParams.searchType === 'all' || searchParams.searchType === 'product' || !searchParams.searchType 
                ? `http://localhost:3000/api/products?${queryParams.toString()}`
                : null;
            
            if (productsUrl) {
                const productsResponse = await fetch(productsUrl);
                if (productsResponse.ok) {
                    const products = await productsResponse.json();
                    products.forEach(product => {
                        allData.push({
                            type: 'product',
                            id: product.id,
                            name: product.name,
                            description: product.description,
                            created_at: product.created_at,
                            photo: product.photo,
                            origin: product.origin || '未知',
                            productionDate: product.production_date || (product.created_at ? product.created_at.split('T')[0] : ''),
                            producer: product.producer || '未知',
                            price: product.price || '',
                            supplier: product.supplier || '',
                        });
                    });
                }
            }
            
        } catch (error) {
            console.error('获取数据失败:', error);
            throw error;
        }
        
        return allData;
    }
    
    function filterData(data, params) {
        return data.filter(item => {
            // 类型过滤
            if (params.searchType && params.searchType !== 'all' && item.type !== params.searchType) {
                return false;
            }
            
            // 名称过滤
            if (params.searchName && !item.name.toLowerCase().includes(params.searchName.toLowerCase())) {
                return false;
            }
            
            // 日期范围过滤
            if (params.startDate && item.productionDate < params.startDate) {
                return false;
            }
            if (params.endDate && item.productionDate > params.endDate) {
                return false;
            }
            
            // 产地过滤
            if (params.origin && !item.origin.includes(params.origin)) {
                return false;
            }
            
            // 分类过滤（仅对食材有效）
            if (params.category && item.category && item.category !== params.category) {
                return false;
            }
            
            return true;
        });
    }
    
    function displayResults(results) {
        if (results.length === 0) {
            resultsContainer.innerHTML = '<p>未找到匹配的数据</p>';
        } else {
            let html = '';
            results.forEach(item => {
                // 增强图片渲染逻辑，防止无效路径
                const getPhotoUrl = (photo) => {
                  if (!photo) return '';
                  if (typeof photo !== 'string') return '';
                  const trimmed = photo.trim();
                  if (!trimmed) return '';
                  // 标准外链
                  if (/^https?:\/\//i.test(trimmed)) {
                    return trimmed;
                  }
                  // 只要包含冒号但不是http/https开头的，都视为无效
                  if (trimmed.includes(':')) return '';
                  // 防止只有斜杠或无效路径（如/300x300/）
                  if (/^\/?[0-9]+x[0-9]+\/?$/.test(trimmed)) return '';
                  // 其它情况按本地文件名处理
                  return `http://localhost:3000/uploads/${trimmed}`;
                };
                const photoHtml = item.photo && getPhotoUrl(item.photo) ? `<img src="${getPhotoUrl(item.photo)}" alt="${item.name}" style="max-width: 100px; max-height: 100px; margin: 10px 0;">` : '';
                
                html += `
                    <div class="result-item">
                        <h4>${item.name}</h4>
                        ${photoHtml}
                        <p><strong>类型：</strong>${getTypeName(item.type)}</p>
                        <p><strong>产地：</strong>${item.origin}</p>
                        <p><strong>创建时间：</strong>${item.created_at}</p>
                        <p><strong>生产单位：</strong>${item.producer}</p>
                        ${item.category ? `<p><strong>分类：</strong>${item.category}</p>` : ''}
                        ${item.price ? `<p><strong>价格：</strong>${item.price}</p>` : ''}
                        ${item.supplier ? `<p><strong>供货商：</strong>${item.supplier}</p>` : ''}
                        ${item.description ? `<p><strong>描述：</strong>${item.description}</p>` : ''}
                        ${item.season ? `<p><strong>出产季节：</strong>${item.season}</p>` : ''}
                        ${item.productionDate ? `<p><strong>出产日期：</strong>${item.productionDate}</p>` : ''}
                    </div>
                `;
            });
            resultsContainer.innerHTML = html;
        }
        
        searchResults.style.display = 'block';
    }
    
    function getTypeName(type) {
        const typeNames = {
            'food': '食物',
            'ingredient': '食材',
            'product': '食品'
        };
        return typeNames[type] || type;
    }
    
    function downloadResults() {
        // 1. 获取当前查询参数
        const formData = new FormData(searchForm);
        const searchParams = Object.fromEntries(formData);

        // 2. 判断类型，只允许单一类型导出
        let type = searchParams.searchType;
        if (!type || type === 'all') {
            showCenterModal('请先选择具体的“查询类型”（食物/食材/食品），再导出Excel！');
            return;
        }
        // foods/ingredients/products
        let apiType = '';
        if (type === 'food') apiType = 'foods';
        else if (type === 'ingredient') apiType = 'ingredients';
        else if (type === 'product') apiType = 'products';
        else {
            alert('不支持的类型');
            return;
        }

        // 3. 拼接查询参数
        const queryParams = new URLSearchParams();
        if (searchParams.searchName) queryParams.append('searchName', searchParams.searchName);
        if (searchParams.startDate) queryParams.append('startDate', searchParams.startDate);
        if (searchParams.endDate) queryParams.append('endDate', searchParams.endDate);
        if (searchParams.origin) queryParams.append('origin', searchParams.origin);
        if (searchParams.category) queryParams.append('category', searchParams.category);

        // 4. 弹窗输入文件名
        const defaultName = `${apiType}_export_${new Date().toISOString().slice(0,10)}.xlsx`;
        showCenterPrompt('请输入导出文件名（含.xlsx后缀）：', defaultName, function(filename) {
            if (!filename) return;
            if (!filename.endsWith('.xlsx')) filename += '.xlsx';
            // 5. 调用后端接口
            const token = sessionStorage.getItem('token') || '';
            fetch(`http://localhost:3000/api/backup/${apiType}?${queryParams.toString()}&filename=${encodeURIComponent(filename)}`, {
                method: 'GET',
                headers: { 'Authorization': token }
            })
            .then(response => {
                if (!response.ok) throw new Error('导出失败');
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
                showCenterModal('数据下载成功！');
            })
            .catch(() => {
                showCenterModal('导出失败，您可能没有权限或服务器异常');
            });
        });
        return;
    }
}); 

// 在文件末尾添加showCenterModal函数
function showCenterModal(message, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `<div style="background:#fff;border-radius:12px;box-shadow:0 4px 24px #388e3c22;padding:32px 36px;min-width:320px;text-align:center;">
        <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
        <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
        <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
    </div>`;
    document.body.appendChild(modal);
    document.getElementById('centerModalBtn').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback();
    };
} 

// 在文件末尾添加showCenterPrompt函数
function showCenterPrompt(message, defaultValue, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `
        <div style="background:#fff;border-radius:14px;box-shadow:0 6px 32px #388e3c22;padding:36px 40px;min-width:360px;text-align:center;">
            <div style="font-size:22px;font-weight:700;margin-bottom:14px;color:#388e3c;">提示</div>
            <div style="font-size:17px;margin-bottom:18px;color:#222;">${message}</div>
            <input id="centerPromptInput" type="text" value="${defaultValue || ''}" style="width:90%;padding:8px 10px;font-size:16px;border:1px solid #ccc;border-radius:5px;margin-bottom:24px;outline:none;">
            <br>
            <button id="centerPromptOk" style="background:#4caf50;color:#fff;border:none;border-radius:7px;padding:10px 38px;font-size:17px;cursor:pointer;margin-right:18px;transition:background 0.2s;">确定</button>
            <button id="centerPromptCancel" style="background:#eee;color:#388e3c;border:none;border-radius:7px;padding:10px 38px;font-size:17px;cursor:pointer;transition:background 0.2s;">取消</button>
        </div>
    `;
    document.body.appendChild(modal);
    const input = document.getElementById('centerPromptInput');
    input.focus();
    document.getElementById('centerPromptOk').onclick = function() {
        const value = input.value.trim();
        document.body.removeChild(modal);
        if (callback) callback(value);
    };
    document.getElementById('centerPromptCancel').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback('');
    };
    // 回车提交
    input.onkeydown = function(e) {
        if (e.key === 'Enter') {
            document.getElementById('centerPromptOk').click();
        }
    };
    // 按钮悬停效果
    document.getElementById('centerPromptOk').onmouseover = function() {
        this.style.background = '#388e3c';
    };
    document.getElementById('centerPromptOk').onmouseout = function() {
        this.style.background = '#4caf50';
    };
    document.getElementById('centerPromptCancel').onmouseover = function() {
        this.style.background = '#c8e6c9';
    };
    document.getElementById('centerPromptCancel').onmouseout = function() {
        this.style.background = '#eee';
    };
} 